import { getPage } from '../../utils/config';
import api from '../../utils/api';
import { $empty, $toast, $loading, http, storage, Validate } from '../../utils/utils';
import MCAP from '../../utils/mcaptcha';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        logged: 0,
        phoneNumber: '',
        smsCode: '',
        smsCodeText: '获取验证码',
        smsCodeBtn: true,
        valueCode: '',//输入的短信
        codeStr: '', //生成的验证码
        mcaptcha: '', //输入的验证码
        mcaptchaError: '',
    },

    /**
     * 手机号码 input
     */
    phoneNumberInput(event) {
        this.setData({
            phoneNumberError: '',
            phoneNumber: $empty(event.detail)
        });
    },

    /**
     * 图形验证码 input
     */
    mcaptchaInput(event)  {
        let { mcaptcha, smsCodeBtn, codeStr, mcaptchaError } = this.data;
        mcaptcha = $empty(event.detail);
        mcaptchaError = '';
        if (event.detail.length == 4) {
            if (codeStr.toLowerCase() == $empty(event.detail).toLowerCase()){
                smsCodeBtn = false
            }else{
                mcaptchaError = '图片验证码错误'
            }
        }
        this.setData({ mcaptchaError, mcaptcha, smsCodeBtn })
    },

    /**
     * 图形验证码 blur
     */
    mcaptchaBlur(event) {
        let { codeStr, smsCodeBtn, mcaptchaError } = this.data;
        if (codeStr.toLowerCase() == $empty(event.detail.value).toLowerCase()){
            smsCodeBtn = false;
        }else{
            mcaptchaError = '图片验证码错误'
            smsCodeBtn = true;
        }
        this.setData({ smsCodeBtn, mcaptchaError });
    },

    /**
     * 手机短信验证码 input
     */
    valueCodeInput(event) {
        this.setData({
            valueCodeError: '',
            valueCode: $empty(event.detail)
        });
    },

    /**
     * 获取手机验证码
     */
    getSmsCode() {
        const { phoneNumber, smsCodeBtn, codeStr, mcaptcha } = this.data;
        if (mcaptcha.toLowerCase() == codeStr.toLowerCase()){
            Validate.rules("#phoneNumber", (res) => {
                Validate.check(this, res, {
                    phoneNumber: phoneNumber,
                }, (bool, error) => {
                    //输入手机号码验证成功且不在短信发送过程中
                    if (!smsCodeBtn && bool) {
                        http.post(api.default, {
                            data: {
                                action: 'send_updatemobile_sms',
                                mobile: phoneNumber
                            }
                        }).then((res) => {
                            let times = 60;
                            let countInter = setInterval(() => {
                                if (times >= 1) {
                                    times--;
                                    this.setData({
                                        smsCodeTimes: times
                                    });
                                } else {
                                    /**
                                     * 获取过期
                                     */
                                    this.initDraw();
                                    this.setData({
                                        smsCodeBtn: false,
                                        smsCodeText: '重新获取',
                                        smsCodeTimes: '',
                                    });
                                    clearInterval(countInter);
                                }
                            }, 1000);
                            this.setData({
                                smsCode: res.data.data,
                                smsCodeBtn: true,
                                smsCodeText: ' 秒后重发',
                                smsCodeTimes: 60,
                            });
                            //提示短信发送成功
                            $toast('短信发送成功', {
                                icon: 'success'
                            });
                        });
                    } else {
                        //弹出提示手机号码验证错误
                        $toast(error[0].msg);
                    }
                }, false);
            });
        }else{
            this.setData({
                mcaptchaError: '图片验证码错误'
            })
        }
    },

    /**
     * 手机号/短信码登录 form
     */
    phoneFormSubmit(event) {
        Validate.check(this, this.phoneValidate, event.detail.value, (res) => {
            const { logged, phoneNumber, smsCode, valueCode, userId, userInfo } = this.data;
            //验证数据通过且未登录
            if (res && !logged) {
                //已获取过验证码
                if (smsCode) {
                    //输入验证码与获取验证码一致
                    if (valueCode === smsCode) {
                        //判断是否登录
                        http.post(api.default, {
                            data: {
                                action: 'updatemobile',
                                mobile: phoneNumber,
                                code: valueCode,
                                userid: userId,
                            }
                        }).then((res) => {
                            userInfo.data.user.mobile_phone = phoneNumber;
                            storage.set('userInfo', userInfo);
                            const pages = getCurrentPages()[getCurrentPages().length - 2];
                            //修改成功
                            $toast(`修改成功`, {
                                icon: 'success'
                            });
                            wx.navigateBack({
                                delta: 1,
                                success() {
                                    if (pages !== undefined || pages !== null) {
                                        pages.onLoad();
                                    }
                                }
                            });
                        });
                    } else {
                        //验证码错误
                        $toast('短信验证码错误，请重新输入');
                    }
                } else {
                    //未获取重新获取
                    $toast('请获取短信验证码');
                }
            }
        });
    },

    /**
     * 改变验证码
     */
    changCapture() {
        this.initDraw();
    },

    /**
     * 制作验证码
     */
    initDraw() {
        let codes = this.getRanNum();
        this.setData({
            codeStr: codes //生成的验证码
        })
        new MCAP({
            el: 'canvas',
            width: 80,
            height: 30,
            code: codes
        });
    },

    /**
     * 随机
     */
    getRanNum: function () {
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var pwd = '';
        for (var i = 0; i < 4; i++) {
            if (Math.random() < 48) {
                pwd += chars.charAt(Math.random() * 48 - 1);
            }
        }
        return pwd;
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.setNavigationBarTitle({
            title: options.title
        })
        app.getLogin().then((res) => {
            this.setData({
                userInfo: res,
                userId: res.data.user.user_id
            });
        }).catch((res) => {
            this.setData({
                logged: res
            })
        });
        /**
         * 手机登录切换后获取数据
         */
        Validate.rules("#phoneNumber,#mcaptcha,#smsCode", (res) => {
            this.phoneValidate = res;
        });
        /**
         * 初始化图片验证码
         */
        this.initDraw();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})